'use server'

import { db } from '@/db'
import { post } from '@/db/schema'
import { auth } from '@/lib/auth'
import { slugify } from '@/lib/utils'
import { and, eq, ne } from 'drizzle-orm'
import { revalidatePath } from 'next/cache'
import { headers } from 'next/headers'

export async function createPost(formData: FormData) {
  try {
    const session = await auth.api.getSession({
      headers: await headers()
    })

    if (!session || !session?.user) {
      return {
        success: false,
        message: 'You must be signed in to create a post'
      }
    }

    const title = formData.get('title') as string
    const description = formData.get('description') as string
    const content = formData.get('content') as string
    const slug = slugify(title)

    const existingPost = await db.query.post.findFirst({
      where: eq(post.slug, slug)
    })

    if (existingPost) {
      return {
        success: false,
        message: 'Post with this title already exists'
      }
    }

    const [newPost] = await db
      .insert(post)
      .values({
        title,
        description,
        content,
        slug,
        authorId: session.user.id
      })
      .returning()

    revalidatePath('/')
    revalidatePath(`/posts/${slug}`)
    revalidatePath('/profile')

    return {
      success: true,
      message: 'Post created successfully',
      slug
    }
  } catch (e) {
    return {
      success: false,
      message: 'Post creation failed'
    }
  }
}

export async function updatePost(postId: number, formData: FormData) {
  try {
    const session = await auth.api.getSession({
      headers: await headers()
    })

    if (!session || !session?.user) {
      return {
        success: false,
        message: 'You must be signed in to update a post'
      }
    }

    const title = formData.get('title') as string
    const description = formData.get('description') as string
    const content = formData.get('content') as string
    const slug = slugify(title)

    const existingPost = await db.query.post.findFirst({
      where: and(eq(post.slug, slug), ne(post.id, postId))
    })

    if (existingPost) {
      return {
        success: false,
        message: 'Post with this title already exists'
      }
    }

    await db
      .update(post)
      .set({
        title,
        description,
        content,
        slug,
        updatedAt: new Date()
      })
      .where(eq(post.id, postId))

    revalidatePath('/')
    revalidatePath(`/posts/${slug}`)
    revalidatePath('/profile')

    return {
      success: true,
      message: 'Post updated successfully',
      slug
    }
  } catch (e) {
    return {
      success: false,
      message: 'Post update failed'
    }
  }
}

export async function deletePost(postId: number) {
  try {
    const session = await auth.api.getSession({
      headers: await headers()
    })

    if (!session || !session?.user) {
      return {
        success: false,
        message: 'You must be signed in to delete a post'
      }
    }

    const postToDelete = await db.query.post.findFirst({
      where: eq(post.id, postId)
    })

    if (!postToDelete) {
      return {
        success: false,
        message: 'Post not found'
      }
    }

    if (postToDelete.authorId !== session.user.id) {
      return {
        success: false,
        message: 'You must be the author of the post to delete it'
      }
    }

    await db.delete(post).where(eq(post.id, postId))

    revalidatePath('/')
    revalidatePath('/profile')

    return {
      success: true,
      message: 'Post deleted successfully'
    }
  } catch (e) {
    return {
      success: false,
      message: 'Post deletion failed'
    }
  }
}
